<?php

namespace app\sysuser\controller\course;

use app\common\controller\SysBackend;
use app\common\enums\ArticleTTlStatusEnum;
use app\common\enums\CourseDataTypeEnum;
use app\common\model\banxi\course\CourseArticle as CourseArticleModel;
use app\common\model\banxi\course\CourseQuestion;
use app\common\service\TencentVocalService;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

/**
 * 课程字典
 */
class CourseArticle extends SysBackend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new CourseArticleModel();
    }

    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->getListPage($where, $pageParams['page'], $pageParams['limit']);
        $this->ok('操作成功', result_row($list));
    }

    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('查询条件不能为空');
        }
        $where = get_query($param);
        $info = $this->model->getInfo($where);
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $this->ok('操作成功', removeNull($info));
    }

    public function saveOrUpdate()
    {
        $param = $this->request->param();
        try {
            $this->model->saveOrUpdate($param);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    public function del()
    {
        $param = $this->request->param(['ids']);
        try {
            $validate = Validate::rule([
                'ids' => ValidateRule::isRequire(null, '请选择你要删除的记录'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $this->model->del($param['ids']);
            (new CourseQuestion)->removeByData($param['ids'], CourseDataTypeEnum::ARTICLE);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    public function generateArticleAudioFromScratch()
    {
        $param = $this->request->param();
        try {
            $this->model->generateAudioFromScratch($param);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    public function detectArticleAudio()
    {
        $param = $this->request->param();
        $tencentVocalService = new TencentVocalService();
        $taskStatus = $tencentVocalService->longTextToSpeechResultQuery($param['ttlTaskId']);
        if (!$taskStatus) {
            $this->fail($tencentVocalService->getError());
        }
        $status = $taskStatus->getStatus();
        $ttlStatus = ArticleTTlStatusEnum::E0;
        switch ($status) {
            case 1:
                $ttlStatus = ArticleTTlStatusEnum::E1;
                break;
            case 2:
                $ttlStatus = ArticleTTlStatusEnum::E2;
                break;
            case 3:
                $ttlStatus = ArticleTTlStatusEnum::E3;
                break;
        }
        $this->model->update([
            'ttlStatus' => $ttlStatus,
        ], ['id' => $param['id']]);
        if ($status == 0) {
            $this->ok('音频生成等待中,请耐心等待', [], self::NOTIFICATION);
        } else if ($status == 1) {
            $this->ok('音频生成执行中,请耐心等待', [], self::NOTIFICATION);
        } else if ($status == 2) {
            $voiceCallback = json_decode($taskStatus->toJsonString(), true);
            $tencentVocalService = new TencentVocalService();
            $voiceUrl = $tencentVocalService->longTextToVoiceCallback($voiceCallback);
            if(!$voiceUrl){
                $this->fail($tencentVocalService->getError());
            }
            $this->model->update(['contentVoice' => $voiceUrl], ['id' => $param['id']]);
            $this->ok('音频生成成功', [], self::NOTIFICATION);
        } else if ($status == 3) {
            $this->fail('音频生成失败');
        }
        $this->ok('未知状态', [], self::ERROR);
    }


}